package frm.billingAndPaymentProcessing.session;

import java.io.IOException;
import java.util.Collection;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;

@Stateless
public class EJBTimerSession implements EJBTimerSessionLocal {

    private final String TIMER_NAME_60000MS = "EJB_TIMER_60000MS";
    private final int TIMER_DURATION_60000MS = 60000;
    @Resource
    private SessionContext ctx;
    @PersistenceContext
    private EntityManager entityManager;
  
    
    
    public EJBTimerSession() {
    }

    @Override
    public void createTimers() {
        TimerService timerService = ctx.getTimerService();
        
        Timer timer60000ms = timerService.createTimer(TIMER_DURATION_60000MS, TIMER_DURATION_60000MS, new String(TIMER_NAME_60000MS));
        System.out.println("********** 60000MS Timer created: " + String.valueOf(timer60000ms.getTimeRemaining()) + ", " + timer60000ms.getInfo().toString());
    }

    @Override
    public void cancelTimers() {
        TimerService timerService = ctx.getTimerService();
        Collection timers = timerService.getTimers();
        for (Object obj : timers) {
            Timer timer = (Timer) obj;
            if (timer.getInfo().toString().equals(TIMER_NAME_60000MS)) {
                timer.cancel();
                System.out.println("********** 60000MS Timer cancelled");
            }
        }
    }

    @Timeout
    public void handleTimeout(Timer timer) throws IOException {
        if (timer.getInfo().toString().equals(TIMER_NAME_60000MS)) {
            handleTimeout_60000ms();
        } else {
            System.out.println("********** Unknown Timer timedout: " + timer.getInfo().toString());
        }
    }

    private void handleTimeout_60000ms() throws IOException {
        HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        request.getSession().invalidate();
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Session is Expired Already", ""));    
        FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
        
    }
}
